//package com.rede.didiok.user.service.impl;
//
//import java.util.ArrayList;
//import java.util.Date;
//import java.util.List;
//import java.util.Map;
//import java.util.concurrent.TimeUnit;
//import java.util.stream.Collectors;
//
//import javax.annotation.Resource;
//
//import cn.hutool.core.bean.BeanUtil;
//import org.springframework.stereotype.Service;
//import org.springframework.transaction.annotation.Transactional;
//
//import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
//import com.baomidou.mybatisplus.core.metadata.IPage;
//import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
//import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
//import com.mysql.cj.protocol.x.Notice;
//import com.rede.didiok.common.constant.conf.MessageConf;
//import com.rede.didiok.common.constant.conf.RedisConf;
//import com.rede.didiok.common.constant.conf.SQLConf;
//import com.rede.didiok.common.constant.conf.SysConf;
//import com.rede.didiok.common.constant.global.Constants;
//import com.rede.didiok.common.dto.user.UserEquityRecordDto;
//import com.rede.didiok.common.enums.EquityTypeEnum;
//import com.rede.didiok.common.enums.StatusEnum;
//import com.rede.didiok.common.enums.UseStatusEnum;
//import com.rede.didiok.common.exception.exceptionType.InsertException;
//import com.rede.didiok.common.exception.exceptionType.QueryException;
//import com.rede.didiok.common.utils.*;
//import com.rede.didiok.common.utils.business.RabbitMqUtil;
//import com.rede.didiok.user.dao.UserEquityRecordDao;
//import com.rede.didiok.user.entity.UserEquityRecordEntity;
//import com.rede.didiok.user.service.NoticeService;
//import com.rede.didiok.user.service.UserEquityRecordService;
//import com.rede.didiok.user.service.UserService;
//
//
//@Service("userEquityRecordService")
//public class UserEquityRecordServiceImpl extends ServiceImpl<UserEquityRecordDao, UserEquityRecordEntity> implements UserEquityRecordService {
//
//    @Resource
//    SystemConfigService systemConfigService;
//    @Resource
//    RabbitMqUtil rabbitMqUtil;
//    @Resource
//    NoticeService noticeService;
//    @Resource
//    SysParamsService sysParamsService;
//    @Resource
//    UserService userService;
//    @Resource
//    RedisUtil redisUtil;
//    @Resource
//    private UserEquityRecordService userEquityRecordService;
//
//    @Override
//    public IPage<UserEquityRecordEntity> getPageList(UserEquityRecordDto userEquityRecordDto) {
//        Page<UserEquityRecordEntity> page = new Page<>();
//        page.setCurrent(userEquityRecordDto.getCurrentPage());
//        page.setSize(userEquityRecordDto.getPageSize());
//        return userEquityRecordService.page(page, fill(userEquityRecordDto));
//    }
//
//    @Override
//    public List<UserEquityRecord> getList(UserEquityRecordVO userEquityRecordVO) {
//        return userEquityRecordService.list(fill(userEquityRecordVO));
//    }
//
//    @Override
//    public Integer getCount(UserEquityRecordVO userEquityRecordVO) {
//        return userEquityRecordService.count(fill(userEquityRecordVO));
//    }
//
//    @Transactional(
//            rollbackFor = {Exception.class}
//    )
//    @Override
//    public Boolean useSignInCards(String userUid, Long cardCount) {
//        UserEquityRecordDto userEquityRecordVO = new UserEquityRecordDto();
//        userEquityRecordVO.setCreateUserUid(userUid);
//        userEquityRecordVO.setEquityType(EquityTypeEnum.SIGN_IN_CARD.getType());
//        userEquityRecordVO.setUseStatus(Constants.STR_ZERO);
//        userEquityRecordVO.setEndTime(new Date());
//        userEquityRecordVO.setIsAsc(Constants.ASC);
//        userEquityRecordVO.setCurrentPage(1L);
//        userEquityRecordVO.setPageSize(cardCount);
//        IPage<UserEquityRecordEntity> userEquityRecordPage = getPageList(userEquityRecordVO);
//        List<UserEquityRecordEntity> userEquityRecordList = userEquityRecordPage.getRecords();
//        if (userEquityRecordList.size() < cardCount) {
//            throw new QueryException("您的补签卡不足");
//        }
//        List<UserEquityRecordEntity> useUserEquityRecords = userEquityRecordList.stream().map(s -> {
//            s.setUseStatus(Integer.valueOf(UseStatusEnum.USED));
//            return s;
//        }).collect(Collectors.toList());
//        // 批量消耗签到卡
//        Boolean isSave = userEquityRecordService.updateBatchById(useUserEquityRecords);
//        return isSave;
//    }
//
//    @Override
//    public Boolean sendSignInCards(String userUid, int cardCount) {
//        if (cardCount <= 0) {
//            throw new InsertException(MessageConf.PARAM_INCORRECT);
//        }
//        List<UserEquityRecord> userEquityRecordList = new ArrayList<>();
//        for (int a = 0; a < cardCount; a++) {
//            userEquityRecordList.add(getSignInCard(userUid));
//        }
//        boolean isSave = userEquityRecordService.saveBatch(userEquityRecordList);
//        return isSave;
//    }
//
//    @Override
//    public void addUserEquityRecord(UserEquityRecordVO userEquityRecordVO) {
//        int count = userEquityRecordVO.getCount() == 0 ? 1: userEquityRecordVO.getCount();
//
//        // 发放用户权益
//        for (int a=0; a< count; a++) {
//            UserEquityRecord userEquityRecord = new UserEquityRecord();
//            BeanUtil.copyProperties(userEquityRecordVO, userEquityRecord, SysConf.STATUS);
//            userEquityRecord.insert();
//        }
//    }
//
//    @Override
//    public Boolean batchSendSignInCard() {
//        String topN = sysParamsService.getSysParamsValueByKey(SysConf.USER_TOP_N);
//        // 获取topN的用户
//        Page<User> page = new Page<>();
//        page.setCurrent(Constants.NUM_ONE);
//        page.setSize(Integer.parseInt(topN));
//        IPage<User> userIPage = userService.page(page, new LambdaQueryWrapper<User>()
//                .eq(User::getStatus, EStatus.ENABLE)
//                .orderByDesc(User::getCredits)
//        );
//        List<String> userUidList = userIPage.getRecords().stream().map(user -> user.getUid()).collect(Collectors.toList());
//        // 获取到目标用户
//        int index = 0;
//        List<UserEquityRecord> userEquityRecordList = new ArrayList<>();
//        for (String userUid : userUidList) {
//            // 前20名，可以获取两张
//            if (index < 20) {
//                userEquityRecordList.add(getSignInCard(userUid));
//                userEquityRecordList.add(getSignInCard(userUid));
//            } else {
//                userEquityRecordList.add(getSignInCard(userUid));
//            }
//            index++;
//        }
//        boolean isSave = userEquityRecordService.saveBatch(userEquityRecordList);
//
//        if (isSave) {
//            // TODO签到卡方法成功，通知用户
//            List<Notice> noticeList = new ArrayList<>();
//            for (UserEquityRecord userEquityRecord : userEquityRecordList) {
//                Notice notice = new Notice();
//                notice.setUserUid(userEquityRecord.getUserUid());
//                notice.setNoticeStatus(0);
//                notice.setContent("恭喜你！通过每周排行榜" + EBusinessType.SEND_SIGN_IN_CARD.getName());
//                notice.setNoticeType(ENoticeType.SYSTEM.getCode());
//                notice.setBusinessUid(userEquityRecord.getUid());
//                notice.setBusinessType(EBusinessType.SEND_SIGN_IN_CARD.getCode());
//                noticeList.add(notice);
//
//                // 用户收到系统通知
//                String redisKey = RedisConf.USER_RECEIVE_SYSTEM_NOTICE_COUNT + Constants.SYMBOL_COLON + userEquityRecord.getUserUid();
//                String count = redisUtil.get(redisKey);
//                if (StringUtils.isNotEmpty(count)) {
//                    redisUtil.incrBy(redisKey, Constants.NUM_ONE);
//                } else {
//                    redisUtil.setEx(redisKey, Constants.STR_ONE, 7, TimeUnit.DAYS);
//                }
//            }
//
//            // 批量发送站内信
//            log.info("批量发送签到卡发放的站内信");
//            noticeService.saveBatch(noticeList);
//
//            // 签到卡发放成功，通知运营人员
//            SystemConfig systemConfig = systemConfigService.getConfig();
//            if (systemConfig != null && EOpenStatus.OPEN.equals(systemConfig.getStartEmailNotification())) {
//                if (StringUtils.isNotEmpty(systemConfig.getEmail())) {
//                    log.info("签到卡发放通知");
//                    String emailContent = "";
//                    String dateTimeStr = DateUtils.dateTimeToStr(new Date());
//                    emailContent = dateTimeStr + " 签到卡发放成功~";
//                    rabbitMqUtil.sendSimpleEmail(systemConfig.getEmail(), emailContent);
//                } else {
//                    log.error("网站没有配置通知接收的邮箱地址！");
//                }
//            }
//        }
//        return isSave;
//    }
//
//    /**
//     * 获取用户签到卡
//     *
//     * @param userUid
//     * @return
//     */
//    private UserEquityRecord getSignInCard(String userUid) {
//        UserEquityRecord userEquityRecord = new UserEquityRecord();
//        userEquityRecord.setUseStatus(EUseStatus.UNUSED);
//        userEquityRecord.setUserUid(userUid);
//        userEquityRecord.setEquityType(EquityType.SIGN_IN_CARD.getType());
//        userEquityRecord.setIsPermanent(Constants.STR_ZERO);
//        // 发放的签到卡，只有一个月的有效期
//        userEquityRecord.setStartTime(new Date());
//        userEquityRecord.setEndTime(DateUtils.getDate(DateUtils.getNowTime(), 31));
//        return userEquityRecord;
//    }
//
//    /**
//     * 填充数据
//     *
//     * @param userEquityRecordVO
//     * @return
//     */
//    private QueryWrapper fill(UserEquityRecordDto userEquityRecordDto) {
//
//        QueryWrapper<UserEquityRecordEntity> queryWrapper = new QueryWrapper<>();
//        queryWrapper.eq(SQLConf.STATUS, StatusEnum.ENABLE);
//        if (StringUtils.isNotEmpty(userEquityRecordDto.getCreateUserUid())) {
//            queryWrapper.eq(SQLConf.CREATE_USER_UID, userEquityRecordDto.getCreateUserUid());
//        }
//        if (StringUtils.isNotEmpty(userEquityRecordDto.getEquityUid())) {
//            queryWrapper.eq(SQLConf.EQUITY_UID, userEquityRecordDto.getEquityUid());
//        }
//        if (StringUtils.isNotEmpty(userEquityRecordDto.getEquityType())) {
//            queryWrapper.eq(SQLConf.EQUITY_TYPE, userEquityRecordDto.getEquityType());
//        }
//        if (StringUtils.isNotEmpty(userEquityRecordDto.getIsPermanent())) {
//            queryWrapper.eq(SQLConf.IS_PERMANENT, userEquityRecordDto.getIsPermanent());
//        }
//        if (StringUtils.isNotEmpty(userEquityRecordDto.getUseStatus())) {
//            queryWrapper.eq(SQLConf.USE_STATUS, userEquityRecordDto.getUseStatus());
//        }
//        if (userEquityRecordDto.getStartTime() != null) {
//            queryWrapper.ge(SQLConf.START_TIME, userEquityRecordDto.getStartTime());
//        }
//        if (userEquityRecordDto.getStartTime() != null) {
//            queryWrapper.eq(SQLConf.END_TIME, userEquityRecordDto.getEndTime());
//        }
//        if (userEquityRecordDto.isAsc()) {
//            queryWrapper.orderByAsc(SQLConf.CREATE_TIME);
//        } else {
//            queryWrapper.orderByDesc(SQLConf.CREATE_TIME);
//        }
////
////         LambdaQueryWrapper<UserEquityRecord> queryWrapper = new LambdaQueryWrapper<UserEquityRecord>()
////                .eq(UserEquityRecord::getStatus, EStatus.ENABLE)
////                .eq(UserEquityRecord::getUserUid, userEquityRecordVO.getUserUid())
////                .eq(UserEquityRecord::getEquityUid, userEquityRecordVO.getEquityUid())
////                .eq(UserEquityRecord::getEquityType, userEquityRecordVO.getEquityType())
////                .eq(UserEquityRecord::getIsPermanent, userEquityRecordVO.getIsPermanent())
////                .eq(UserEquityRecord::getUseStatus, userEquityRecordVO.getUseStatus())
////                .ge(UserEquityRecord::getStartTime, userEquityRecordVO.getStartTime())
////                .le(UserEquityRecord::getEndTime, userEquityRecordVO.getEndTime());
////        if(userEquityRecordVO.isAsc()) {
////            queryWrapper.orderByAsc(UserEquityRecord::getCreateTime);
////        } else {
////            queryWrapper.orderByDesc(UserEquityRecord::getCreateTime);
////        }
//        return queryWrapper;
//    }
//}